package evcs

import (
	"encoding/json"
	"evtest/util"
	"fmt"
	"strings"
	"sync/atomic"
	"time"
)

type Sequence struct {
	count     int32
	timestamp int
}

var sequence Sequence

func init() {
	sequence.count = 1
	sequence.timestamp = time.Now().Second()
}

type EvcsReq struct {
	OperatorID string
	Data       string
	TimeStamp  string
	Seq        string
	Sig        string
}

func NewEvcsReq(operatorID string) *EvcsReq {
	if sequence.timestamp != time.Now().Second() {
		sequence.count = 1
		sequence.timestamp = time.Now().Second()
	} else {
		atomic.AddInt32(&sequence.count, 1)
	}
	return &EvcsReq{
		OperatorID: operatorID,
		TimeStamp:  time.Now().Format("20060102150405"),
		Seq:        fmt.Sprintf("%04d", sequence.count),
	}
}

func (evcsReq *EvcsReq) EncryptData(data []byte, aesKey string, ivStr string) {
	encryptData, _ := util.AESBase64Encrypt(data, aesKey, ivStr)
	evcsReq.Data = encryptData
}

func (evcsReq *EvcsReq) Sign(hmacKey string) {
	strToBeSigned := evcsReq.OperatorID + evcsReq.Data + evcsReq.TimeStamp + evcsReq.Seq
	evcsReq.Sig = strings.ToUpper(util.Hmac(hmacKey, strToBeSigned))
}

func (evcsReq *EvcsReq) ToJson() ([]byte, error) {
	return json.Marshal(evcsReq)
}

type QueryToken struct {
	OperatorID     string
	OperatorSecret string
}

func (queryToken *QueryToken) ToJson() ([]byte, error) {
	return json.Marshal(queryToken)
}

type QueryStationsInfo struct {
	LastQueryTime string `json:"LastQueryTime,omitempty"`
	PageNo        int
	PageSize      int
}

func (queryStationsInfo *QueryStationsInfo) ToJson() ([]byte, error) {
	return json.Marshal(queryStationsInfo)
}
